﻿// -----------------------------------------------------------------------
//  <copyright file="IdentityController.cs" company="柳柳软件">
//      Copyright (c) 2014-2015 66SOFT. All rights reserved.
//  </copyright>
//  <site>http://www.66soft.net</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2015-12-24 1:46</last-date>
// -----------------------------------------------------------------------

using System.ComponentModel;
using System.Threading.Tasks;
using System.Web.Mvc;

using OSharp.Web.Mvc.UI;

using ZH.JY.Identity;
using ZH.JY.Identity.Dtos;
using ZH.JY.Identity.Models;
using ZH.JY.Web.Security;


namespace ZH.JY.Web.Controllers
{
    [Description("网站-账户认证")]
    public class IdentityController : Controller
    {
        /// <summary>
        /// 获取或设置 用户管理器
        /// </summary>
        public UserManager UserManager { get; set; }

        /// <summary>
        /// 获取或设置 账户登录管理
        /// </summary>
        public SignInManager SignInManager { get; set; }

        [HttpPost]
        [Description("网站-账户认证-用户登录")]
        public async Task<ActionResult> Login(LoginInfo loginInfo)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult("提交信息验证失败", AjaxResultType.Error));
            }
            if (!SecurityHelper.CheckVerify(loginInfo.VerifyCode, true))
            {
                return Json(new AjaxResult("验证码错误，请刷新后重试", AjaxResultType.Error));
            }
            User user = await UserManager.FindByNameAsync(loginInfo.UserName);
            if (user == null)
            {
                return Json(new AjaxResult("用户名不存在", AjaxResultType.Error));
            }
            if (!await UserManager.CheckPasswordAsync(user, loginInfo.Password))
            {
                return Json(new AjaxResult("用户名或密码不正确", AjaxResultType.Error));
            }
            await SignInManager.SignInAsync(user, loginInfo.Remember, true);
            var data = new
            {
                User = new { UserId = user.Id, user.UserName, user.NickName, user.Email },
                SessionId = Session.SessionID
            };
            return Json(new AjaxResult("登录成功", AjaxResultType.Success, data));
        }
    }
}